package quantri.qltv;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import utils.StringUtils;
import utils.UtilsOnScopes;

import dbutil.ConnectDB;
import dbutil.DBUtils;

/******************************************
 * Filename			: User.java
 * Decription		:
 * Created date		: Jun 7, 2008
 * Author			: Phonglt
 ******************************************/
public class User {
	private String id="0";
	private String stt;
	private String tenDangNhap = "";
	private String matKhau = "";
	private String xacNhanMK = "";
	private String hoTen = "";
	private String dienThoai = "";
	private String hopThu = "";
	private String diaChi = "";
	private String flag = "";
	private String error="" ;
	private List<User> listUser;

	public User() {
	}

	public User(String stt, String tenDangNhap, String matKhau,
			String xacNhanMK, String hoTen, String dienThoai, String hopThu,
			String diaChi) {
		this.stt = stt;
		this.tenDangNhap = tenDangNhap;
		this.matKhau = matKhau;
		this.xacNhanMK = xacNhanMK;
		this.hoTen = hoTen;
		this.dienThoai = dienThoai;
		this.hopThu = hopThu;
		this.diaChi = diaChi;
	}

	private boolean checkEmail(String email){
		boolean result  = true;
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher matcher = p.matcher(email);
		result = matcher.matches();
		return result ;
	}
	private boolean checknumberPhone(String numberPhone){
		boolean result  = true;
		if((numberPhone.length() < 7) || (numberPhone.length() > 12)){
			return result = false;
		}else
		{
			try{
				char[] arr = numberPhone.toCharArray();
				int number = 0;
				for (int i = 0; i < arr.length; i++) {
				    number = Integer.parseInt(String.valueOf(arr[i]));
					if(number < 0){
						result = false;
					}					
				}
			}catch(Exception e){
				e.printStackTrace();
				return result = false;
			}
		}
		return result ;
	}
	
	private boolean checkValue(){
		boolean result = true;
		if(this.tenDangNhap == null || this.tenDangNhap.equals("")){
			this.setError("Bạn chưa nhập tên đăng nhập !");
			return result = false;
		}
		else if(!(this.hopThu.equals(""))){
			if(this.checkEmail(this.hopThu) == false)
			{
				this.setError("Hộp thư không đúng !");
				return result = false;
			}	
		}
		else if (!(this.dienThoai.equals("")))
		{
			if(this.checknumberPhone(this.dienThoai) == false)
			{
				this.setError("Số điện thoại không đúng !");
				return result = false;
			}
		}
		return result;
	}
	
	/***************************************************************************
	 * Method name : save Return type : String Decription :luu thanh vien xuong
	 * CSDL Created date : Jun 6, 2008 Author : Honglk
	 **************************************************************************/
	public String save() {
		ConnectDB.connectDB();
		String result = "";
		try {
			// kiem tra xem record insert vao co trong csdl hay chua?
			// neu co roi thi khong insert
			String SQL = " SELECT COUNT(*) AS count FROM thanhvien "
					+ " WHERE id='"+this.id + "' OR  name='" + this.tenDangNhap + "'";
			ArrayList<HashMap<String, Object>> array = ConnectDB
					.getDataTypeList(SQL);
			HashMap<String, Object> hash = (HashMap<String, Object>) array
					.get(0);
			int count = Integer.parseInt(hash.get("count").toString());
			//kiem tra cac truong 
			if(this.checkValue() == false){
				return "";
			}
			else if(count > 0 && (this.id.equals("0"))){
				this.setError("Tên đăng nhập: "+this.tenDangNhap+ " này đã tồn tại !");
				return this.error;
			}
			else if (count == 0 && !(this.tenDangNhap.equals(""))) {
				// luu xuong
				PreparedStatement preStat = ConnectDB.connect
						.prepareStatement("INSERT INTO thanhvien(name,diachi,mail,phone,pass,hoten) "
								+ "VALUES(?,?,?,?,?,?)");
				preStat.setString(1, this.tenDangNhap);
				preStat.setString(2, this.diaChi);
				preStat.setString(3, this.hopThu);
				preStat.setString(4, this.dienThoai);
				// ma hoa pass truoc khi luu
				String encryptPass = utils.StringUtils
						.encryptString(this.tenDangNhap);
				preStat.setString(5, encryptPass);
				preStat.setString(6, this.hoTen);
				preStat.executeUpdate();
				this.setError("Bạn đã đăng ký thành công !");
				result = "okTaoThanhVien";
				// dung de sua thông tin
			} else if ( count > 0 && !(this.id.equals("0"))) {
				PreparedStatement preStat = ConnectDB.connect
						.prepareStatement("UPDATE thanhvien SET name=?,diachi=?,mail=?,phone=?,hoten=?"
								+ " WHERE id='" +this.id +"'");
				preStat.setString(1, this.tenDangNhap);
				preStat.setString(2, this.diaChi);
				preStat.setString(3, this.hopThu);
				preStat.setString(4, this.dienThoai);
				preStat.setString(5, this.hoTen);
				preStat.executeUpdate();
				this.setError("Bạn đã cập nhật thành công !");
				result = "okTaoThanhVien";
			}
		} catch (Exception e) {
			this.setError("Đăng ký không thành công !");
			e.printStackTrace();
		}
		this.reset1();
		return result;
	}

	/***************************************************************************
	 * Method name : delete Return type : String Decription :Xóa thành viên
	 * Created date : Jun 6, 2008 Author : Honglk
	 **************************************************************************/
	public String delete() {
		this.setError("");
		try {
			HttpServletRequest request = UtilsOnScopes.getRequest();
			String id = request.getParameter("id");
			String SQL = "SELECT COUNT(B.idthanhvien) AS count FROM quyenchucnang B WHERE " +
					   " B.idthanhvien = (SELECT A.id FROM thanhvien A WHERE A.id='"+id+"')";
			ArrayList<HashMap<String, Object>> array = ConnectDB
					.getDataTypeList(SQL);
			HashMap<String, Object> hash = (HashMap<String, Object>) array
					.get(0);
			int count = Integer.parseInt(hash.get("count").toString());
			System.out.println(SQL);
			if (count > 0) {
				this.setError("Người dùng này đã được phân quyền!");
				return this.error;
			}else if(count == 0){
				DBUtils.deleteData("thanhvien", "id", id);
				this.setError("Xóa thành công!");
			}
		
		} catch (Exception e) {
		}
		return "okTaoThanhVien";

	}

	public String edit() {
		this.setError("");
		HttpServletRequest request = UtilsOnScopes.getRequest();
		String id = request.getParameter("id");
		String flag = StringUtils.nullToString(request.getParameter("flag"));
		String tenDangNhap = StringUtils.nullToString(request
				.getParameter("tenDangNhap"));
		String matKhau = StringUtils.nullToString(request
				.getParameter("matKhau"));
		String xacNhanMK = StringUtils.nullToString(request
				.getParameter("xacNhanMK"));
		String hoTen = StringUtils.nullToString(request.getParameter("hoTen"));
		String dienThoai = StringUtils.nullToString(request
				.getParameter("dienThoai"));
		String hopThu = StringUtils
				.nullToString(request.getParameter("hopThu"));
		String diaChi = StringUtils
				.nullToString(request.getParameter("diaChi"));
		if ((!(id.equals(""))) || id != null) {
			this.setFlag(flag);
			this.setId(id);
			this.setTenDangNhap(tenDangNhap);
			this.setDiaChi(diaChi);
			this.setHopThu(hopThu);
			this.setDienThoai(dienThoai);
			this.setMatKhau(matKhau);
			this.setXacNhanMK(xacNhanMK);
			this.setHoTen(hoTen);

		}
		return "okTaoThanhVien";
	}

	/***************************************************************************
	 * Method name : reset Return type : String Decription :Reset Created date :
	 * Jun 7, 2008 Author : Honglk
	 **************************************************************************/
	public String reset() {
		UtilsOnScopes.getSession().removeAttribute("userQLTV");
		this.setTenDangNhap("");
		this.setDiaChi("");
		this.setDienThoai("");
		this.setHopThu("");
		this.setMatKhau("");
		this.setXacNhanMK("");
		this.setHoTen("");
		this.setId("0");
		this.setError("");
		return "okTaoThanhVien";
	}
	public String reset1() {
		this.setTenDangNhap("");
		this.setDiaChi("");
		this.setDienThoai("");
		this.setHopThu("");
		this.setMatKhau("");
		this.setXacNhanMK("");
		this.setHoTen("");
		this.setId("0");
		return "okTaoThanhVien";
	}

	/***************************************************************************
	 * Method name : displayListUser Return type : String Decription :Hien thi
	 * ra table đông thời la hàm search Created date : Jun 6, 2008 Author :
	 * Honglk
	 **************************************************************************/
	public String displayListUser() {
		
		this.setError("");
		List<User> list = new ArrayList<User>();
		String SQL = "SELECT * FROM thanhvien WHERE "
				+ this.searchHelp(this.tenDangNhap, this.dienThoai, this.hoTen)
				+ "  ORDER BY hoten";
		ArrayList<HashMap<String, Object>> array = ConnectDB
				.getDataTypeList(SQL);
		if (array.size() > 0) {
			HashMap<String, Object> hash = new HashMap<String, Object>();
			int stt = 0;
			for (int i = 0; i < array.size(); i++) {
				stt = i + 1;
				hash = (HashMap<String, Object>) array.get(i);
				User user = new User();
				user.setTenDangNhap(hash.get("name").toString());
				user.setDiaChi(hash.get("diachi").toString());
				user.setHopThu(hash.get("mail").toString());
				user.setDienThoai(hash.get("phone").toString());
				user.setMatKhau(hash.get("pass").toString());
				user.setXacNhanMK(hash.get("pass").toString());
				user.setHoTen((hash.get("hoten") == null) ? "" : (hash
						.get("hoten").toString()));
				user.setId(hash.get("id").toString());
				user.setStt(String.valueOf(stt));
				list.add(user);
			}
		}
		this.setListUser(list);
		return "okTaoThanhVien";
	}

	/***************************************************************************
	 * Method name : searchHelp Return type : String Decription :Hỗ trợ cho hàm
	 * search Created date : Jun 6, 2008 Author : Honglk
	 **************************************************************************/
	public String searchHelp(String userName, String phone, String fullName) {
		StringBuffer buffer = new StringBuffer();
		String strTemp = "";
		String strTempCond1 = "TRIM(LOWER(name)) LIKE TRIM(LOWER('%" + userName
				+ "%')) OR '" + (userName.equals("") ? "1" : userName)
				+ "'='1'";
		String strTempCond2 = "phone= '" + phone + "' OR '"
				+ (phone.equals("") ? "1" : phone) + "'= '1'";
		String strTempCond3 = "TRIM(LOWER(hoten)) LIKE TRIM(LOWER('%"
				+ fullName + "%')) OR '"
				+ (fullName.equals("") ? "1" : fullName) + "'='1'";

		strTemp = "(" + strTempCond1 + ") AND (" + strTempCond2 + ") "
				+ " AND (" + strTempCond3 + ")";
		buffer.append("(");
		buffer.append(strTemp);
		buffer.append(")");
		return buffer.toString();
	}

	public String getStt() {
		return stt;
	}

	public void setStt(String stt) {
		this.stt = stt;
	}

	public String getTenDangNhap() {
		return tenDangNhap;
	}

	public void setTenDangNhap(String tenDangNhap) {
		this.tenDangNhap = tenDangNhap;
	}

	public String getMatKhau() {
		return matKhau;
	}

	public void setMatKhau(String matKhau) {
		this.matKhau = matKhau;
	}

	public String getXacNhanMK() {
		return xacNhanMK;
	}

	public void setXacNhanMK(String xacNhanMK) {
		this.xacNhanMK = xacNhanMK;
	}

	public String getHoTen() {
		return hoTen;
	}

	public void setHoTen(String hoTen) {
		this.hoTen = hoTen;
	}

	public String getDienThoai() {
		return dienThoai;
	}

	public void setDienThoai(String dienThoai) {
		this.dienThoai = dienThoai;
	}

	public String getHopThu() {
		return hopThu;
	}

	public void setHopThu(String hopThu) {
		this.hopThu = hopThu;
	}

	public String getDiaChi() {
		return diaChi;
	}

	public void setDiaChi(String diaChi) {
		this.diaChi = diaChi;
	}

	public List<User> getListUser() {
		this.displayListUser();
		return listUser;
	}

	public void setListUser(List<User> listUser) {
		this.listUser = listUser;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public static void main(String[] args) {
		User user = new User();
//		System.out.println(user.searchHelp("kimhong", "0938147547",
//				"le kim hong"));
		//System.out.println(user.checkEmail("hong@y.com"));
		System.out.println(user.checknumberPhone("093814754e"));
	}

}